'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require('path')
class UploadController extends Controller {
    // 服务的 上传
    async adminUpload() {
        const ctx = this.ctx;
        const {id}=ctx.request.body
        console.log(ctx.request.files);
        if (!ctx.request.files || ctx.request.files.length==0) {
            return ctx.apiFail('请先选择上传文件');
        }
        const file = ctx.request.files[0];
        // const name = 'egg-oss-demo/' + path.basename(file.filename);
        const name = 'egg-yhq/admin/' + id + '/' + ctx.getCode(10) + path.extname(file.filename);
        let result;
        try {
            result = await ctx.oss.put(name, file.filepath);
        } catch (err) {
            console.log(err);
        } finally {
            await fs.unlink(file.filepath);
        }
        if (result) {
            return ctx.apiSuccess(result.url);
        }

        ctx.apiFail('上传失败');
    }
}

module.exports = UploadController;
